<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Listener;

use App\Model\User;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Event\ValidatorFactoryResolved;

/**
 * 自定义验证规则类 可以根据项目定义多条验证规则
 * Class SelfValidationRuleListener.
 * @Listener
 */
class SelfValidationRuleListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            ValidatorFactoryResolved::class,
        ];
    }

    public function process(object $event)
    {
        /**
         * @var ValidatorFactoryInterface $validatorFactory
         */
        $validatorFactory = $event->validatorFactory;
        //注册手机验证器
        $validatorFactory->extend('mobile', function ($attribute, $value, $parameters, $validator) {
            return boolval(preg_match('/^1[345789][0-9]{9}$/', $value));
        });
        // 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符这里扩展了 :foo 占位符
        $validatorFactory->replacer('mobile', function ($message, $attribute, $rule, $parameters) {
            return str_replace(':mobile', $attribute, $message);
        });
        //注册手机验证器 end

        $validatorFactory->extend('check_user_isset', function ($attribute, $value, $parameters, $validator) {
            $isset = User::find($value, ['user_id']);
            return boolval($isset);
        });
        $validatorFactory->replacer('check_user_isset', function ($message, $attribute, $rule, $parameters) {
            return str_replace(':check_user_isset', $attribute, $message);
        });
    }
}
